import axios from 'axios'
import Qs from 'qs'
import router from '@/router'
import store from '@/store'
import {
  MessageBox,
  Message
} from 'element-ui'
import {
  getToken
} from '@/utils/auth'

// 全局的 axios 默认值
axios.defaults.baseURL = process.env.VUE_APP_BASE_API; // url = base url + request url
axios.defaults.withCredentials = true; // 表示跨域请求时是否需要使用凭证
axios.defaults.timeout = 60000; // 指定请求超时的毫秒数(0 表示无超时时间)
axios.defaults.responseType = 'json';
axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded';

// create an axios instance
const service = axios.create({
  transformRequest: [function(data, headers) {
    return Qs.stringify(data)
  }],
})

// request interceptor
service.interceptors.request.use(
  config => {
    config.headers['Authentication'] = getToken();
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data
    const message = res.message
    const code = String(res.code)

    //接口返回异常的code
    if (code !== '0') {
      //若code为-2 表示token已经失效
      if (code === '-2') {
        Message.closeAll();
        MessageBox.confirm('未登陆或登陆已超时，请重新登录', '登陆提醒', {
          confirmButtonText: '重新登陆',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/logout').then(r => {
            router.push('/login');
          })
        })
      } else {
        Message({
          showClose: true,
          message: message || '系统忙请稍后再试',
          type: 'error',
          center: true,
          duration: 3000
        })
      }

      return Promise.reject(new Error(message || '系统忙请稍后再试'))
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

const request = config => {
  return new Promise((resolve, reject) => {
    service(config).then(response => {
      resolve(response)
    }).catch(error => {
      reject(error)
    })
  })
}

export const uploadFileSync = config => {
  const upConfig = {
    headers: {
      'Content-Type': 'multipart/form-data',
      'Authentication': getToken()
    }
  };
  return new Promise((resolve, reject) => {
    axios.post(config.url, config.formData, upConfig).then(res => {
      resolve(res.data);
    }).catch(err => {
      reject(err);
    })
  })
}

export const getRequest = (url, params) => {
  console.log('getRequest', params)
  return request({
    url: url,
    method: 'get',
    params
  })
}

export const postRequest = (url, data) => {
  console.log('postRequest', data)
  return request({
    url: url,
    method: 'post',
    data
  })
}



export default service
